package com.ytjj.qmyx.supplychain.api.controller;

import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.model.ProductSpecVO;
import com.ytjj.qmyx.supplychain.common.model.request.ProductStockFrozenRequest;
import com.ytjj.qmyx.supplychain.common.model.response.SupplyChainProductSpecStockResponse;
import com.ytjj.qmyx.supplychain.mapper.entity.YxProductSpec;
import com.ytjj.qmyx.supplychain.service.ProductService;
import com.ytjj.qmyx.supplychain.service.StockFrozenRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 库存管理
 */
@RestController
@RequestMapping("/stock")
public class ProductStockController {
    @Resource
    private ProductService productService;
    @Resource
    private StockFrozenRecordService stockFrozenRecordService;

    /**
     * 冻结库存
     * 1.销售端支付完成调用冻结
     * 2.然后供应链发货时解冻库存，真实扣减库存
     * 3.如果售后还需要退还库存
     * @param request
     * @return
     */
    @PostMapping("/frozen")
    public CommonResult productStockFrozen(@RequestBody ProductStockFrozenRequest request) {
        return stockFrozenRecordService.insert(request);
    }

    /**
     * 查询商品状态和指定规格库存
     * @param bankerProductId 供应商商品id
     * @param supplyId 供应链商品规格id
     * @return
     */
    @GetMapping("/get")
    public CommonResult getByProductId(@RequestParam(value = "bankerProductId") Integer bankerProductId,
                                       @RequestParam(value = "supplyId", required = false) Integer supplyId) {
        return productService.queryProductStockAndStatus(bankerProductId, supplyId);
    }

    /**
     * 查询商品状态和所有规格库存总和
     * @param bankerProductId
     * @return
     */
    @GetMapping("/getByProduct")
    public CommonResult getStockByProduct(@RequestParam(value = "bankerProductId") Integer bankerProductId) {
        return productService.queryProductAllStockAndStatus(bankerProductId);
    }


    /**
     * 更新库存冻结状态(调用这个方法后 还需要调用下面的subAndAddStock方法)
     * @param orderNo 订单编号
     * @param status 更新状态值 2-已扣库存 3-退还库存 4-冻结作废(超时未支付或取消支付)
     * @return
     */
    @GetMapping("/updateProductStock")
    public boolean updateProductStock(@RequestParam(value = "orderNo") String orderNo,
                                       @RequestParam(value = "status") Integer status) {
        return stockFrozenRecordService.updateStatusByOrderNo(orderNo,status);
    }

    /**
     * 扣减或退还库存
     * @param num 商品数量
     * @param type sub-扣减 add-退还
     * @return
     */
    @GetMapping("/subAndAddStock")
    public boolean subAndAddStock(@RequestParam(value = "orderNo")  String orderNo,
                                  @RequestParam(value = "num") Integer num,
                                  @RequestParam(value = "isZeroProduct") Integer isZeroProduct,
                                  @RequestParam(value = "type") String type){
        return stockFrozenRecordService.subAndAddStock(orderNo,num,isZeroProduct,type);
    }

    /**
     * 转单后扣减或退还库存
     * @param num 商品数量
     * @param type sub-扣减 add-退还
     * @return
     */
    @GetMapping("/subAndAddStockForTransfer")
    public boolean subAndAddStockForTransfer(@RequestParam(value = "productId") Integer productId,
                                             @RequestParam(value = "productSpecId") Integer productSpecId,
                                             @RequestParam(value = "num") Integer num,
                                             @RequestParam(value = "type") String type) {
        return stockFrozenRecordService.subAndAddStockForTransfer(productId, productSpecId, num, type);
    }

    /**
     * 根据供应商商品id查询供应链商品库存
     * @param bankerProductIds 供应商商品id（多个用‘,’分隔）
     * @return
     */
    @GetMapping("/querySupplyProductStockByBankerProductId")
    public CommonResult querySupplyProductStockByBankerProductId(@RequestParam("bankerProductIds") String bankerProductIds) {
        List<String> bankerProductIdList = Arrays.asList(bankerProductIds.split(","));
        List<Integer> bankerProductIdList_Integer = bankerProductIdList.stream().map(Integer::parseInt).collect(Collectors.toList());

        List<YxProductSpec> productSpecs = productService.querySupplyProductStockByBankerProductIds(bankerProductIdList_Integer);

        List<SupplyChainProductSpecStockResponse> dataList = new ArrayList<>();
        bankerProductIdList_Integer.stream().forEach(bankerProductId -> {
            List<YxProductSpec> productSpecList = productSpecs.stream().filter(e -> bankerProductId.equals(e.getBankerProductId())).collect(Collectors.toList());
//            List<YxProductSpec> productSpecList = productService.querySupplyProductStockByBankerProductId(bankerProductId);
            SupplyChainProductSpecStockResponse response = new SupplyChainProductSpecStockResponse();
            response.setBankerProductId(bankerProductId);

            List<ProductSpecVO> voList = new ArrayList<>();
            if (null == productSpecList) {
                response.setProductSpecList(voList);
                dataList.add(response);
                return;
            }
            productSpecList.stream().forEach(item -> {
                ProductSpecVO vo = new ProductSpecVO();
                BeanUtils.copyProperties(item, vo);
                voList.add(vo);
            });
            response.setProductSpecList(voList);
            dataList.add(response);
        });
        return CommonResult.success(dataList);
    }
}
